package com.scheduler;

import com.dao.OrderDao;
import com.service.OrderService;
import com.service.impl.OrderServiceImpl;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.PersistJobDataAfterExecution;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

@DisallowConcurrentExecution
@PersistJobDataAfterExecution
public class QuartzJob extends QuartzJobBean {
    private SqlSession sqlSession;

    public void mybatisConfig() {
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream("mybatis.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        sqlSession = new SqlSessionFactoryBuilder().build(inputStream).openSession(true);
    }

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        mybatisConfig();
        OrderDao orderDao = sqlSession.getMapper(OrderDao.class);
        Date date = new Date();
        System.out.println("每1分钟修改超时订单为失效状态，执行时间：" + date);
        date.setTime(date.getTime() - 30 * 60 * 1000);
        System.out.println("在该时间之后都失效：" + date);
        if (orderDao.countByOrderTime(date) > 0) {
            int i = orderDao.updateByDate(date);
            System.out.println("修改成功，影响数据为：" + i);
        }
    }

}
